<!-- 综合查询页面 -->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="货源方名" prop="companyId">
        <el-select v-model="queryParams.companyId" filterable  placeholder="请输入助记码" clearable size="mini">
          <el-option
            v-for="item in opCompany"
            :key="item.id"
            :label="item.nameCode"
            :value="item.id">
            <span style="float: left">{{ item.shortName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.fullName }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="司机姓名" prop="driverId">
        <el-select v-model="queryParams.driverId" filterable  placeholder="请输入助记码" clearable size="mini">
          <el-option
            v-for="item in opDriver"
            :key="item.id"
            :label="item.driverName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="流水时间" prop="rangeDate">
        <el-date-picker
          v-model="queryParams.rangeDate"
          type="daterange"
          size="mini"
          value-format="yyyy-MM-dd"
          range-separator="-"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['tws:apply:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div class="avue-group__header">
      <i class="iconfont iconzhijiandan-"></i>
      <h1 class="avue-group__title">
        销售收入：
        <label style="color:green">{{income>0?income.toFixed(2):income}}</label>元
        （核销：
        <label style="color:green">{{incomePaid>0?incomePaid.toFixed(2):incomePaid}}</label>元）
      </h1>
      <h1 class="avue-group__title">
        销售支出：
        <label style="color:rgb(255, 176, 59)">{{outcome>0?outcome.toFixed(2):outcome}}</label>元
        （核销：
        <label style="color:rgb(255, 176, 59)">{{outcomePaid>0?outcomePaid.toFixed(2):outcomePaid}}</label>元）
      </h1>
      <h1 class="avue-group__title">
        未收：
        <label style="color:red">{{(income-incomePaid-outcome+outcomePaid).toFixed(2)}}</label>元
      </h1>
      <h1 class="avue-group__title">
        毛利润：
        <label style="color:red">{{(income-outcome).toFixed(2)}}</label>元
      </h1>
    </div>

    <el-table v-loading="loading" :data="applyList">
      <el-table-column label="货源方名称" align="center" prop="companyName" min-width="100" show-overflow-tooltip />
      <el-table-column label="司机姓名" align="center" prop="driverName" />
      <el-table-column label="应收金额" align="center" prop="amount" >
        <template slot-scope="scope">
          <span>{{scope.row.ysAmount.toFixed(2)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="应收核销金额" align="center" prop="ysPaidAmount" >
        <template slot-scope="scope">
          <span>{{scope.row.ysPaidAmount.toFixed(2)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="未收金额" align="center" prop="ysPaidAmount" >
        <template slot-scope="scope">
          <span>{{ (scope.row.ysAmount.toFixed(2) - scope.row.ysPaidAmount.toFixed(2)).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="应付金额" align="center" prop="yfAmount" >
        <template slot-scope="scope">
          <span>{{scope.row.yfAmount.toFixed(2)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="应付核销金额" align="center" prop="yfPaidAmount" >
        <template slot-scope="scope">
          <span>{{scope.row.yfPaidAmount.toFixed(2)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="未付金额" align="center" prop="yfPaidAmount" >
        <template slot-scope="scope">
          <span>{{ (scope.row.yfAmount.toFixed(2) - scope.row.yfPaidAmount.toFixed(2)).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="毛利润" align="center" prop="yfPaidAmount" >
        <template slot-scope="scope">
          <span>{{ (scope.row.ysAmount.toFixed(2) - scope.row.yfAmount.toFixed(2)).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view"
                     @click="flowShow(scope.row)">明细</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 明细对话框 -->
    <el-dialog title="明细" :visible.sync="open" width="90%" append-to-body>
      <div class="avue-group__header">
        <el-form :model="listParams" ref="query2Form" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="收入支出" prop="flag">
            <el-select
              v-model="listParams.flag"
              placeholder="请选择收入支出"
              clearable
              size="mini"
              @keyup.enter.native="handle2Query"
            >
              <el-option
                v-for="dict in inOutOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="流水类型" prop="flowType">
            <el-cascader placeholder="请选择流水类型编号"
                         v-model="listParams.flowType"
                         :options="paymentFlowTypeOption"
                         size="mini"
                         :props="{ expandTrigger: 'hover',children:'children' }"
                         @change="handleChange">
            </el-cascader>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="listParams.status"
              placeholder="请选择状态"
              clearable
              size="mini"
              @keyup.enter.native="handleQuery"
            >
              <el-option
                v-for="dict in flowStatusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="流水时间" prop="rangeDate">
            <el-date-picker
              v-model="listParams.rangeDate"
              type="daterange"
              size="mini"
              value-format="yyyy-MM-dd"
              range-separator="-"
            ></el-date-picker>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handle2Query">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="reset2Query">重置</el-button>
          </el-form-item>
        </el-form>

        <i class="iconfont iconzhijiandan-"></i>

        <h1 class="avue-group__title">
          销售收入：
          <label style="color:green">{{income2>0?income2.toFixed(2):income2}}</label>元
          （核销：
          <label style="color:green">{{incomePaid2>0?incomePaid2.toFixed(2):incomePaid2}}</label>元）
        </h1>
        <h1 class="avue-group__title">
          销售支出：
          <label style="color:rgb(255, 176, 59)">{{outcome2>0?outcome2.toFixed(2):outcome2}}</label>元
          （核销：
          <label style="color:rgb(255, 176, 59)">{{outcomePaid2>0?outcomePaid2.toFixed(2):outcomePaid2}}</label>元）
        </h1>
        <h1 class="avue-group__title">
          未收：
          <label style="color:red">{{(income2-incomePaid2-outcome2+outcomePaid2).toFixed(2)}}</label>元
        </h1>
        <h1 class="avue-group__title">
          毛利润：
          <label style="color:red">{{(income2-outcome2).toFixed(2)}}</label>元
        </h1>
      </div>

      <el-table v-loading="listLoading" :data="flowList" max-height="500">
        <el-table-column label="#" type ="index"></el-table-column>
        <el-table-column label="货源方" align="center" prop="companyName" />
        <el-table-column label="司机" align="center" prop="driverName" />
        <el-table-column label="车牌号" align="center" prop="plate" />
        <el-table-column label="流水类型" align="center" prop="flowType" :formatter="flowTypeFormat" />
        <el-table-column label="金额" align="center" prop="amount" >
          <template slot-scope="scope">
            <span>{{scope.row.amount.toFixed(2)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="已核销金额" align="center" prop="paidAmount" min-width="100" >
          <template slot-scope="scope">
            <span>{{scope.row.paidAmount.toFixed(2)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="收入支出" align="center" prop="flag" :formatter="inOutFormat" />
        <el-table-column label="状态" align="center" prop="status" :formatter="flowStatusFormat"/>
        <el-table-column label="流水日" align="center" prop="flowDate" width="110">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.flowDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="listTotal>0"
        :total="listTotal"
        :page.sync="listParams.current"
        :limit.sync="listParams.size"
        @pagination="getFlowList"
      />
    </el-dialog>
  </div>
</template>

<script>
  import { getCurrentMonthFirstDay, getCurrentMonthLastDay } from "@/utils/date";
  import { listCompanyAll } from "@/api/tws/company";
  import { listDriverAll } from "@/api/tws/driver";
  // import { flowStatementAll, getFlowAllProfit, flowStatement } from "@/api/tws/chart";
  // import { getFeeType, getFlowType } from "@/api/tws/paymentFlowType";
  // import { listFlow } from "@/api/tws/flow";

  export default {
    name: "FlowAll",
    components: {
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        listLoading: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        listTotal: 0,
        income: 0,
        incomePaid: 0,
        outcome: 0,
        outcomePaid: 0,
        income2: 0,
        incomePaid2: 0,
        outcome2: 0,
        outcomePaid2: 0,
        //货源方
        opCompany:[],
        //查询与流水用司机
        opDriver:[],
        paymentFlowTypeOption:[],
        // 表格数据
        applyList: [],
        // 明细表格数据
        flowList: [],
        // 流水类型
        flowTypeList: [],
        // 流水类型
        flowTypeTreeList: [],
        // 是否显示弹出层
        open: false,
        // 流水状态
        flowStatusOptions: [],
        // 收入支出数据字典
        inOutOptions: [],
        // 查询参数
        queryParams: {
          current: 1,
          size: 10,
          status: null,
          companyId: null,
          companyName: null,
          driverId: null,
          driverName: null,
          types: '2,3,4',
          rangeDate: [getCurrentMonthFirstDay(), getCurrentMonthLastDay()]
        },
        listParams: {
          current: 1,
          size: 10,
          flag: null,
          status: null,
          flowType: null,
          companyId: null,
          companyName: null,
          driverId: null,
          driverName: null,
          types: '2,3,4',
          rangeDate: [getCurrentMonthFirstDay(), getCurrentMonthLastDay()]
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {}
      };
    },
    created() {
      // // 查询流水类型
      // this.getFlowTypeList();
      // /** 查询货源方 */
      // this.getCompanyList();
      // /** 查询司机 */
      // this.getDriverList();
      // this.getList();
    },
    methods: {
      /** 综合查询列表 */
      getList() {
        console.log("执行getList")
        this.loading = true;
        /** 综合查询列表 */
        flowStatementAll(this.queryParams).then(response => {
          this.applyList = response.rows;
          console.log(this.applyList)
          this.total = response.total;
          this.loading = false;
        });
        /** 综合查询列表 -全部利润统计 */
        getFlowAllProfit(this.queryParams).then(res => {
          if (res.code == 200) {
            this.income = res.data.income;
            this.outcome = res.data.outcome;
            this.incomePaid = res.data.incomePaid;
            this.outcomePaid = res.data.outcomePaid;
          } else {
            this.$message.error("获取数据出错");
          }
        });
      },
      /** 查询货源方 */
      getCompanyList(){
        let obj = {
          isCert: '2',
          state: '1'
        }
        listCompanyAll(obj).then(res => {
          if(res.code == 200){
            this.opCompany = res.data;
            this.opCompany.forEach(element =>{
              element.value = element.fullName;
              //为助记码匹配
              element.nameCode = element.shortCode + '-' + element.fullName;
            })
          }
        });
      },
      /** 获取司机信息 */
      getDriverList(){
        let obj = {
          isCert: '2',
          state: '1'
        }
        listDriverAll(obj).then(res => {
          if(res.code == 200){
            this.opOwnerAll = res.data;
            this.opDriver = res.data;

            //为助记码匹配
            this.opOwnerAll.forEach( evn => {
              evn.codeName = evn.code + '-' + evn.name;
            })
            //console.log(this.opOwnerAll);
          }
        });
      },
      // 查询流水类型
      getFlowTypeList(){
        getFlowType().then(res=>{
          this.flowTypeList = res.data;
          res.data.forEach(element => {
            let com = {
              label:element.name,
              value:element.id,
              type:element.type
            };
            this.flowTypeTreeList.push(com);
          });
          this.paymentFlowTypeOption.forEach(item=>{
            item.children = this.flowTypeTreeList.filter(ele=>ele.type==item.value)
          })
          var str = JSON.stringify(this.paymentFlowTypeOption);
          this.paymentFlowTypeOption = JSON.parse(str);
        })
      },
      // 流水状态字典翻译
      flowStatusFormat(row, column) {
        return this.selectDictLabel(this.flowStatusOptions, row.status);
      },
      // 收入支出字典翻译
      inOutFormat(row, column) {
        return this.selectDictLabel(this.inOutOptions, row.flag);
      },
      // 流水类型翻译
      flowTypeFormat(row, column) {
        if (row.flowType) {
          const flowT = this.flowTypeList.find(item => item.id == row.flowType);
          console.log("翻译",flowT)
          if (flowT) {
            return flowT.name
          }
        }
      },
      handleChange(value) {
        this.listParams.flowType = value[1];
      },
      // 明细按钮
      flowShow(row){
        this.resetForm("query2Form");
        this.listParams.companyId = row.companyId;
        this.listParams.driverId = row.driverId;
        this.getFlowList();
        this.open = true;
      },
      /** 查询明细列表 */
      getFlowList() {
        this.listLoading = true;
        /** 查询明细列表 */
        flowStatement(this.listParams).then(response => {
          console.log("查询明细列表:",response)
          this.flowList = response.rows;
          this.listTotal = response.total;
          this.listLoading = false;
        });
        // 查询弹窗的统计
        getFlowAllProfit(this.listParams).then(res => {
          if (res.code == 200) {
            this.income2 = res.data.income;
            this.outcome2 = res.data.outcome;
            this.incomePaid2 = res.data.incomePaid;
            this.outcomePaid2 = res.data.outcomePaid;
          } else {
            this.$message.error("获取数据出错");
          }
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          title: null,
          applyNo: null,
          isBill: null,
          billUserId: null,
          billUser: null,
          billType: null,
          billNo: null,
          billDate: null,
          amount: null,
          paidAmount: null,
          tax: null,
          status: 0,
          createUserName: null,
          createBy: null,
          createTime: null,
          flag: null,
          companyId: null,
          driverId: null,
          companyName: null,
          driverName: null,
          type: null,
          tenantId: null,
          updateBy: null,
          updateTime: null,
          delFlag: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.current = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 明细弹窗搜索按钮操作 */
      handle2Query() {
        this.listParams.current = 1;
        this.getFlowList();
      },
      /** 明细弹窗重置按钮 */
      reset2Query() {
        this.resetForm("query2Form");
        this.handle2Query();
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('tws/statistic/export', {
          ...this.queryParams
        }, `tws_apply.xlsx`)
      }
    }
  };
</script>

<style scoped>
  .avue-group__header {
    display: inline-block;
    margin-bottom: 10px;
    border-bottom: 1px solid #C0C0C0;
  }
  .avue-group__title {
    display: inline-block;
    font-size: 15px;
    padding: 0 0 0 6px;
  }
</style>
